package com.arrogames.blondbattle.game.purchases 
{
	import ash.core.Engine;
	import ash.core.NodeList;
	import ash.core.System;
	import com.arrogames.blondbattle.game.purchases.Reward;
	import com.arrogames.blondbattle.game.state.CommanderNode;
	import com.arrogames.blondbattle.game.purchases.RewardNode;
	import org.as3commons.logging.api.getLogger;
	import org.as3commons.logging.api.ILogger;
	
	/**
	 * ...
	 * @author Robin van den Bogaard
	 */
	public class RewardingSystem extends System {
		
		private static const logger:ILogger = getLogger(RewardingSystem);
		
		private var commanderNodes:NodeList;
		private var rewardNodes:NodeList;
		
		public function RewardingSystem() {
			super();
		}
		
		override public function addToEngine(engine:Engine):void {
			super.addToEngine(engine);
			commanderNodes = engine.getNodeList(CommanderNode);
			rewardNodes = engine.getNodeList(RewardNode);
			rewardNodes.nodeRemoved.add(nodeRemoved);
		}
		
		private function nodeRemoved(node:RewardNode):void {
			var cNode:CommanderNode = findOpponentCommander(node.faction.name);
			if (cNode) {
				cNode.money.value += node.reward.value;
				logger.debug("Awarded "+cNode.faction.name+" a reward of "+node.reward.value);
			} else {
				logger.debug("Opponent commander not found, reward gets discarded");
			}
		}
		
		private function findOpponentCommander(name:String):CommanderNode {
			var result:CommanderNode;
			var node:CommanderNode;
			for (node = commanderNodes.head; node && result == null; node = node.next) {
				if (node.faction.name != name) {
					result = node;
				}
			}
			return result;
		}
		
	}

}